import { createRouter, createWebHistory } from 'vue-router'
import Cookies from 'js-cookie'
import store from '@/store'
import { getRouters } from '@/api/login/login'

// 公共路由
export const routes = [
  //角色控制路由
  {
    name: 'Permission',
    path: '/permission',

    meta: {
      keepAlive: true,
      title: "权限管理",
      icon: "UserFilled"
    },
    children: [
      {
        name: 'role',
        path: 'role',
        component: () => import('@/views/role/role'),
        meta: {
          keepAlive: true,
          title: "角色管理"
        },
      },
      {
        name: 'user',
        path: 'user',
        component: () => import('@/views/role/user'),
        meta: {
          keepAlive: true,
          title: "用户管理"
        }
      },
      {
        name: 'tenant',
        path: 'tenant',
        component: () => import('@/views/role/tenant'),
        meta: {
          keepAlive: true,
          title: "租户管理"
        }
      },
    ]
  },
  {
    path: "/",
    redirect: "/home",
    meta: {
      keepAlive: false,
    }
  },
  {
    path: '/1',
    component: () => import('@/views/home/index.vue'),
    name: "1",
    meta: {
      keepAlive: true,
      title: "首页",
    }
  },
  {
    path: '/home',
    component: () => import('@/views/home/home.vue'),
    name: "home",
    meta: {
      keepAlive: true,
      title: "首页"
    }
  },
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/login'),
    hidden: true,
    meta: {
      keepAlive: false,
      title: "登陆"
    }
  },
  {
    name: 'test',
    path: '/test',
    component: () => import('@/views/test'),
    hidden: true,
    meta: {
      keepAlive: true,
      title: "测试"
    }
  },
  {
    name: 'register',
    path: '/register',
    component: () => import('@/views/register'),
    hidden: true,
    meta: {
      keepAlive: false,
      title: "注册"
    }
  },
  //客户路由
  {
    name: 'Custom',
    path: '/custom',

    meta: {
      keepAlive: true,
      title: "客户管理",
      icon: "User"
    },
    children: [
      {
        name: 'supplier',
        path: 'supplier',
        component: () => import('@/views/user/supplier'),
        meta: {
          keepAlive: true,
          title: "供应商管理"
        },
      },
      {
        name: 'custom',
        path: 'custom',
        component: () => import('@/views/user/custom'),
        meta: {
          keepAlive: true,
          title: "借货客户管理"
        }
      },
      {
        name: 'processor',
        path: 'processor',
        component: () => import('@/views/user/processor'),
        meta: {
          keepAlive: true,
          title: "加工厂管理"
        }
      },
    ]
  },
  //销售路由
  {
    name: 'Sale',
    path: '/sale',

    meta: {
      keepAlive: true,
      title: "销售管理",
      icon: "CreditCard"
    },
    children: [
      {
        name: 'lend',
        path: 'lend',
        component: () => import('@/views/sale/lend'),
        meta: {
          keepAlive: true,
          title: "未还列表"
        }
      },
      {
        name: 'return',
        path: 'return',
        component: () => import('@/views/sale/return'),
        meta: {
          keepAlive: true,
          title: "还货列表"
        }
      },
      {
        name: 'saled',
        path: 'saled',
        component: () => import('@/views/sale/saled'),
        meta: {
          keepAlive: true,
          title: "已售列表"
        }
      },
    ],
  },


]

const dynamicRoutes = [

  //销售路由
  {
    name: 'Sale',
    path: '/sale',

    meta: {
      keepAlive: true,
      title: "销售管理",
      icon: "CreditCard"
    },
    children: [
      {
        name: 'lend',
        path: 'lend',
        component: () => import('@/views/sale/lend'),
        meta: {
          keepAlive: true,
          title: "未还列表"
        }
      },
      {
        name: 'return',
        path: 'return',
        component: () => import('@/views/sale/return'),
        meta: {
          keepAlive: true,
          title: "还货列表"
        }
      },
      {
        name: 'saled',
        path: 'saled',
        component: () => import('@/views/sale/saled'),
        meta: {
          keepAlive: true,
          title: "已售列表"
        }
      },
    ],
  },

  //库存路由
  {
    name: 'Inventory',
    path: '/inventory',

    meta: {
      keepAlive: true,
      title: "库存管理",
      icon: "Box"
    },
    children: [
      {
        name: 'inventorymanage',
        path: 'manage',
        component: () => import('@/views/inventory/manage'),
        meta: {
          keepAlive: true,
          title: "在仓货物管理"
        },
      },
      {
        name: 'inventoryrecord',
        path: 'record',
        component: () => import('@/views/inventory/record'),
        meta: {
          keepAlive: true,
          title: "货品列表"
        }
      },
    ]
  },

  //排班路由
  {
    name: 'Schedule',
    path: '/pb',
    meta: {
      keepAlive: true,
      title: "排班管理",
      icon: "Timer"
    },
    children: [
      {
        name: 'streamShop',
        path: 'streamShop',
        component: () => import('@/views/schedule/streamShop'),
        meta: {
          keepAlive: true,
          title: "店铺信息管理"
        }
      },
      {
        name: 'schedule',
        path: 'schedule',
        component: () => import('@/views/schedule/schedule'),
        meta: {
          keepAlive: true,
          title: "店铺排班管理"
        },
      },
      {
        name: 'streamHost',
        path: 'streamHost',
        component: () => import('@/views/schedule/streamHost'),
        meta: {
          keepAlive: true,
          title: "主播管理"
        },
      },
    ]
  },

  //入库路由
  {
    name: 'Inbound',
    path: '/inbound',
    meta: {
      keepAlive: true,
      title: "入库管理",
      icon: "Printer"
    },
    children: [
      {
        name: 'inboundaction',
        path: 'action',
        component: () => import('@/views/inbound/action'),

        meta: {
          keepAlive: true,
          title: "采借入库"
        }
      },
      // {
      //   name: 'inboundreturn',
      //   path: 'return',
      //   component: () => import('@/views/inbound/return'),
      //   meta: {
      //     keepAlive: true,
      //     title: "还货入库"
      //   }
      // },
      {
        name: 'inboundreturn',
        path: 'return',
        component: () => import('@/views/inbound/return'),

        meta: {
          keepAlive: true,
          title: "还货入库"
        }
      },
      {
        name: 'inboundorder',
        path: 'order',
        component: () => import('@/views/inbound/order'),
        meta: {
          keepAlive: true,
          title: "入库单列表"
        }
      },
      {
        name: 'inboundjade',
        path: 'goods',
        component: () => import('@/views/inbound/goods'),
        meta: {
          keepAlive: true,
          title: "入库货品列表"
        }
      },
      // {
      //   name: 'inboundaudit',
      //   path: 'audits',
      //   component: () => import('@/views/inbound/audits/index'),
      //   meta: {
      //     keepAlive: true,
      //     title: "库存调整单"
      //   },
      // },
      // {
      //   name: 'inboundchecklist',
      //   path: 'checklist',
      //   component: () => import('@/views/inbound/checklist/index'),
      //   meta: {
      //     keepAlive: true,
      //     title: "盘点单列表"
      //   }
      // },
      // {
      //   name: 'inboundAuditOrder',
      //   path: 'auditOrder',
      //   component: () => import('@/views/inbound/auditOrder'),
      //   meta: {
      //     keepAlive: true,
      //     title: "库存调整"
      //   }
      // },
      // {
      //   name: 'inboundAuditPrice',
      //   path: 'auditPrice',
      //   component: () => import('@/views/inbound/auditPrice'),
      //   meta: {
      //     keepAlive: true,
      //     title: "价格调整"
      //   }
      // }
    ],
  },

  //出库路由
  {
    name: 'Outbound',
    path: '/outbound',

    meta: {
      keepAlive: true,
      title: "出库管理",
      icon: "IconMenu",
    },
    children: [
      {
        name: 'outboundaction',
        path: 'action',
        component: () => import('@/views/outbound/outbound'),
        meta: {
          keepAlive: true,
          title: "出库操作"
        },
      },
      // {
      //   name: 'outboundrecord',
      //   path: 'record',
      //   component: () => import('@/views/outbound/record'),
      //   meta: {
      //     keepAlive: true,
      //     title: "出库货品列表"
      //   }
      // },
      {
        name: 'outboundorder',
        path: 'order',
        component: () => import('@/views/outbound/order'),
        meta: {
          keepAlive: true,
          title: "出库单列表"
        }
      },
    ]
  },


  //系统配置路由
  {
    name: 'System',
    path: '/system',

    meta: {
      keepAlive: true,
      title: "系统设置",
      icon: "Setting"
    },
    children: [
      {
        name: 'warehouse',
        path: 'warehouse',
        component: () => import('@/views/setting/warehouse'),
        meta: {
          keepAlive: true,
          title: "仓库管理"
        }
      },
      {
        name: 'storage',
        path: 'storage',
        component: () => import('@/views/setting/storage'),
        meta: {
          keepAlive: true,
          title: "仓位管理"
        },
      },
      {
        name: 'cipher',
        path: 'cipher',
        component: () => import('@/views/setting/cipher'),
        meta: {
          keepAlive: true,
          title: "暗码设置"
        },
      },
    ]
  },

]
const systemRoutes = [
  //角色控制路由
  {
    name: 'Permission',
    path: '/permission',

    meta: {
      keepAlive: true,
      title: "权限管理",
      icon: "UserFilled"
    },
    children: [
      {
        name: 'role',
        path: 'role',
        component: () => import('@/views/role/role'),
        meta: {
          keepAlive: true,
          title: "角色管理"
        },
      },
      {
        name: 'user',
        path: 'user',
        component: () => import('@/views/role/user'),
        meta: {
          keepAlive: true,
          title: "用户管理"
        }
      },
      {
        name: 'tenant',
        path: 'tenant',
        component: () => import('@/views/role/tenant'),
        meta: {
          keepAlive: true,
          title: "租户管理"
        }
      },
    ]
  },
  //客户路由
  {
    name: 'Custom',
    path: '/custom',

    meta: {
      keepAlive: true,
      title: "客户管理",
      icon: "User"
    },
    children: [
      {
        name: 'supplier',
        path: 'supplier',
        component: () => import('@/views/user/supplier'),
        meta: {
          keepAlive: true,
          title: "供应商管理"
        },
      },
      {
        name: 'custom',
        path: 'custom',
        component: () => import('@/views/user/custom'),
        meta: {
          keepAlive: true,
          title: "借货客户管理"
        }
      },
      {
        name: 'processor',
        path: 'processor',
        component: () => import('@/views/user/processor'),
        meta: {
          keepAlive: true,
          title: "加工厂管理"
        }
      },
    ]
  },

// 盘点管理路由
{
  name: 'inventoryCheck',
  path: '/inbound/inventory-check',
  meta: {
    keepAlive: true,
    title: "盘点管理",
    icon: "Check"  // 使用 "Check" 图标
  },
  children: [
    {
     name: 'inboundchecklist',
     path: 'checklist',
     component: () => import('@/views/inbound/checklist/index'),
     meta: {
       keepAlive: true,
       title: "盘点单列表"
     }
   },
   {
     name: 'inboundaudit',
     path: 'audits',
     component: () => import('@/views/inbound/audits/index'),
     meta: {
       keepAlive: true,
       title: "库存调整单"
     },
   },
 ]
},

// 审核路由
{
  name: 'Check',
  path: '/audit',
  meta: {
    keepAlive: true,
    title: "审核",
    icon: "Edit",
    apiPath: '/getRouters'  // 新增字段，用于指定获取路由信息的 API 路径
  },
  children: [
    {
      name: 'inboundAuditOrder',
      path: 'auditOrder',
      component: () => import('@/views/inbound/auditOrder'),
      meta: {
        keepAlive: true,
        title: "库存调整",
        apiPath: '/getRouters'  // 为子路由也添加相应的 API 路径字段
      }
    },
    {
      name: 'inboundAuditPrice',
      path: 'auditPrice',
      component: () => import('@/views/inbound/auditPrice'),
      meta: {
        keepAlive: true,
        title: "价格调整",
        apiPath: '/getRouters'  // 为子路由也添加相应的 API 路径字段
      }
    }
  ],
}
]

/* 
  页面中动态导入的路由的映射表，可以自己查查为什么不能直接使用import()，然后里面填要动态解析的路由字段,
  这个不是上面那个动态导入，这里指的是生成的临时界面，不需要权限这种，某个页面临时打开某个表
  单又不想用弹窗，希望打开的是能加入界面上方导航路由的一个界面，并且搞下面这些也只是为了实现
  刷新页面也能保存这些临时界面并刷新后呈现，避免丢失路由界面白屏并且无法进行任何操作 
*/

const componentMap = {
  'src/views/inbound/audits/check.vue': () => import('@/views/inbound/audits/check.vue'),
  'src/views/inbound/audits/edit.vue':() => import('@/views/inbound/audits/edit.vue'),
  'src/views/inbound/audits/index.vue':() => import('@/views/inbound/audits/index.vue'),
  'src/views/inbound/checklist/edit.vue':() => import('@/views/inbound/checklist/edit.vue'),
  'src/views/inbound/checklist/create.vue':() => import('@/views/inbound/checklist/create.vue'),
  // 添加其他组件路径映射
};


export const constantRoutes = createRouter({
  history: createWebHistory(),
  routes
})

export async function addRoutes(data) {
  // 清空之前的动态路由
  data.forEach(function (item_d) {
    dynamicRoutes.forEach(function (item_r) {
      if (item_d.name == item_r.name) {
        constantRoutes.removeRoute(item_r.name);
        store.state.routes = store.state.routes.filter(route => route.name !== item_r.name);
      }
    });
  });

  data.forEach(function (item_d) {
    if (item_d.name == 'System') {
      // console.log("systemRoutes:",systemRoutes)
      systemRoutes.forEach(item => {
        // console.log("systemRoutes:",item)
        constantRoutes.addRoute(item)
        store.state.routes.push(item)
      })

    }
    dynamicRoutes.forEach(function (item_r) {
      if (item_d.name == item_r.name) {
        constantRoutes.addRoute(item_r)
        store.state.routes.push(item_r)
      }
    })
  })
}
// 保存当前路由信息到 localStorage
function saveCurrentRoute(to) {
  localStorage.setItem('currentRoute', JSON.stringify(to));
}

// 从 localStorage 获取当前路由信息
function getCurrentRoute() {
  const currentRoute = localStorage.getItem('currentRoute');
  return currentRoute ? JSON.parse(currentRoute) : null;
}
// 在页面加载时从 localStorage 获取并打印刷新前的当前路由
window.addEventListener('load', () => {
  // const currentRoute = getCurrentRoute();这是原代码，这块确实只有这一条原本，我做了个动态自定义路由的判断
  const currentRoute = getCurrentRoute();
  // console.log(currentRoute)
  if ( currentRoute && currentRoute.meta && currentRoute.meta.isDynamic ) { //说明当前页面是动态导入的自定义路由
    const componentPath = currentRoute.matched[0].components.default.__file
    const loadComponent = componentMap[componentPath];// 映射表获取对应路由
    const newRoute = {
      path: currentRoute.path,
      name: currentRoute.name,
      meta: currentRoute.meta,
      component: loadComponent,// 保存组件路径
    };
    constantRoutes.addRoute(newRoute);// 因为直接获取的currentRoute没有component导入
    constantRoutes.push({ path: currentRoute.path, query: currentRoute.meta.query});
    store.commit('addTag', {path: currentRoute.path, title: currentRoute.meta.title, query:currentRoute.meta.query||0 });
  }
});
// 在网页即将刷新或关闭时保存当前路由信息
window.addEventListener('beforeunload', () => {
  // 获取当前活动的路由信息
  const currentRoute = constantRoutes.currentRoute.value;
  saveCurrentRoute(currentRoute);
});
// 在路由切换时保存当前路由信息
constantRoutes.afterEach((to) => {
  saveCurrentRoute(to);
});

// 重置路由和其他状态
function resetParam(state) {
  state.routes.values = [];
  state.sidebarOpened = true;
  state.tagsViewList = [
    {
      path: '/home',
      title: '首页'
    }
  ];
}

// 退出登录时重置路由和其他状态
export function logoutRouter() {
  resetParam(store.state);
  localStorage.removeItem('currentRoute');
}
constantRoutes.beforeEach(async (to, from, next) => {
  let isLogin = Cookies.get('isLogin')
  if (to.path == '/login') {//去登录
    next()
  } else if (store.state.routes.length == 0) {
    try {
      const res = await getRouters();
      // console.log("登录后的getRouters():",res)
      if (res) {
        await addRoutes(res.data);
        next({
          ...to,
          replace: true
        });
      } else {
        // ElMessage.error('登录状态已过期，请重新登录');
        // constantRoutes.push(LOGIN_PATH);
      }
    } catch (error) {
      // 错误处理逻辑
    }
  }
  else {
    next()
  }
})

export default constantRoutes;
